<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 商品类目管理
 * @package app\cms\admin
 */
class GoodsClassTemp extends Admin
{
    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		$list = model('ErpGoodsClassTemp', 'model') -> getClass();
		
		$btn_goods = [
			'title' => '查看商品',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('goods/list', ['classtemp_id' => '__id__', '_pop' => 1]),
		];
		
		$btn_access = [
			'title' => '添加',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('add', ['pid' => '__id__']),
		];
		
		$btn_specifications = [
			'title' => '规格设置',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('specifications', ['classtemp_id' => '__id__']),
		];
		
		$btn_parameter = [
			'title' => '参数设置',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('parameter', ['classtemp_id' => '__id__']),
		];
		
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('商品类目') // 设置页面标题
            ->setTableName('erp_goods_classtemp') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', 'id'],
                ['level', '级别'],
				['title_display', '类别名称'],
                ['sort', '排序', 'text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->addFilter(['report_status']) // 添加筛选
			->addTopButton('add', '', true) // 批量添加顶部按钮
			->addRightButton('btn_access', $btn_access, true) // 添加授权按钮
			->addRightButton('btn_specifications', $btn_specifications, true)
			->addRightButton('btn_parameter', $btn_parameter, true) 
			->replaceRightButton(['level' => ['in', '1,2']], '', 'btn_specifications,btn_parameter')
			->replaceRightButton(['level' => 3], '', 'btn_access')
			->replaceRightButton(['level' => ['gt',3]], '', 'btn_access,btn_specifications,btn_parameter,edit,btn_goods')
			->addRightButton('edit', '',true) // 批量添加右侧按钮
			->addRightButton('delete') // 批量添加右侧按钮
			->addRightButton('btn_goods', $btn_goods, true)
			->setRowList($list) // 设置表格数据,
            ->fetch(); // 渲染页面
    }
	
	 /**
     * 新增
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($pid = ''){  
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			
			$pid        	= isset($data['pid']) ? $data['pid'] : '';
			$title    		= isset($data['title']) ? $data['title'] : '';
			$sort 	 		= isset($data['sort']) ? $data['sort'] : '';
			$path 	 		= isset($data['path']) ? $data['path'] : '';
			//数据验证
			$Validate = validate('GoodsClassTemp', 'validate');
			if( !$Validate -> scene('goods_class_add') -> check($data) ){
				$this->error($Validate -> getError());
			}
			
			//业务逻辑
			$map = [];
			$map['pid'] = $pid;
			$map['title'] = $title;
			$class_title = model('ErpGoodsClassTemp') -> where($map) -> find(); //标题
			if(!empty($class_title)){
				$this->error('类别标题重复，无法添加');
			}
			
			$rel = model('ErpGoodsClassTemp') -> addData($pid, $title, $sort);
			if($rel['code'] == 200){
				$id = $rel['data'];
				$path = $id;
				if($pid > 0){
					$father_path = model('ErpGoodsClassTemp') -> find($pid) -> path;//上级path
					$path = $father_path . '-' .$path;//重组path
				}
				model('ErpGoodsClassTemp') -> where('id', $id) -> update(['path' => $path]);
				
				$this->success('新增成功', null, '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增类别')
            ->addFormItems([
                ['select', 'pid', '所属上级', '所属上级分类', model('ErpGoodsClassTemp') -> getMenuTree(0, ''), $pid],
                ['text', 'title', '类别标题'],
            ])
            ->addText('sort', '排序', '', 100)
            ->setTrigger('auto_create', '1', 'child_node', false)
            ->fetch();
    }
	
	/**
     * 编辑
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = 0, $pid = ''){   
		if ($id === 0) $this->error('缺少参数');
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			$data['id'] = $id;
			$pid        	= isset($data['pid']) ? $data['pid'] : '';
			$title    		= isset($data['title']) ? $data['title'] : '';
			$sort 	 		= isset($data['sort']) ? $data['sort'] : '';
			$path 	 		= isset($data['path']) ? $data['path'] : '';
			
			//数据验证
			$Validate = validate('GoodsClassTemp', 'validate');
			if( !$Validate -> scene('goods_class_edit') -> check($data) ){
				$this->error($Validate -> getError());
			}
			
			//业务逻辑
			$map = [
				['id', '<>', $id],
				['pid', '=', $pid],
				['title', '=', $title],
			];
			$list_class = model('ErpGoodsClassTemp') -> where($map) -> find();//标题
			if(!empty($list_class)){
				$this->error('类别标题重复，无法修改');
			}
			
			$rel = model('ErpGoodsClassTemp') -> editData($id ,$pid, $title, $sort);
			if($rel['code'] == 200){
				$new_path = $id;
				if($pid > 0){
					$father_path = model('ErpGoodsClassTemp') -> find($pid) -> path;//上级path
					$new_path = $father_path . '-' .$new_path;//重组path
				}
				$childs_path = model('ErpGoodsClassTemp') -> getChildsPath($id);//所有子集path
				$list = [];
				foreach($childs_path as $key => $value){//下级分类path重组
					$childs_new_path['id'] = $key;
					$childs_new_path['path'] = str_replace($path, $new_path, $value);
					$list[] = $childs_new_path;
				}
				$list[] = ['id' => $id, 'path' => $new_path]; //插入条修改信息
				model('ErpGoodsClassTemp') -> saveAll($list);
				
				$this->success('修改成功', null, '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
		
		$info = model('ErpGoodsClassTemp') -> find($id);
		$class_title = $info['pid'] == '' ? '顶级节点' : model('ErpGoodsClassTemp') -> find($info['pid']) -> title;
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑类别')
            ->addFormItems([
                // ['select', 'pid', '所属上级', '所属上级分类', model('ErpGoodsClassTemp') -> getMenuTree(0, ''), $pid],
                ['text', 'pid_title', '所属上级', '所属上级分类', $class_title, '', 'readonly="readonlys"'],
                ['text', 'title', '类别标题'],
            ])
			->addHidden('pid', $info['pid'])
            ->addText('sort', '排序')
			->addHidden('path')
            ->setTrigger('auto_create', '1', 'child_node', false)
			->setFormData($info)
            ->fetch();
    }
	
	/**
     * 删除
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function delete($ids = []){ 
        $class = model('ErpGoodsClassTemp') -> where('id', $ids)->find();
		
		// 获取所有后辈id
        $class_childs = model('ErpGoodsClassTemp') -> getChildsId($ids);
		// 要删除的所有id
        $all_ids = array_merge([(int)$ids], $class_childs);;
		$rel = model('ErpGoodsClassTemp') -> destroy($all_ids);
        if ($rel) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
	
	
	/**
     * 规格设置
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function specifications($classtemp_id = ''){  
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			$specifications_id 	= isset($data['specifications_id']) ? $data['specifications_id'] : [];
			if(count($specifications_id) > 2 || count($specifications_id) < 2){
				$this -> error('请选择规格 且必须为两项');
			}
			$old_sid = model('ErpGoodsClasstempSpecifications') -> where('classtemp_id', $classtemp_id) -> column('id');//查出原有关联 并删除
			$rel = model('ErpGoodsClasstempSpecifications') -> deleteData($old_sid);
			if(empty($old_sid) || $rel['code'] == 200){
				foreach($specifications_id as $sid){
					$rel = model('ErpGoodsClasstempSpecifications') -> addData($classtemp_id, $sid);//插入新的关联规格id
					if($rel['code'] < 0){
						$this->error($rel['message']);
					}
				}
				$this->success('设置成功', null, '_parent_reload');
			}
			$this->error($rel['message']);
		}
		
		$specifications_id = model('ErpGoodsClasstempSpecifications') -> where('classtemp_id', $classtemp_id) -> column('specifications_id');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('规格设置')
			->addCheckbox('specifications_id', '选择规格', '选择规格不能超过2项', model('ErpSpecifications', 'model') -> column('id,title'), $specifications_id, 'multiple')
            ->setTrigger('auto_create', '1', 'child_node', false)
            ->fetch();
    }
	
	/**
     * 参数设置
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function parameter($classtemp_id = ''){  
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			$parameter_id 	= isset($data['parameter_id']) ? $data['parameter_id'] : [];
			if(count($parameter_id) > 20){
				$this -> error('请选择参数且不能超过20项');
			}
			$old_sid = model('ErpGoodsClasstempParameter') -> where('classtemp_id', $classtemp_id) -> column('id');//查出原有关联 并删除
			$rel = model('ErpGoodsClasstempParameter') -> deleteData($old_sid);
			if(empty($old_sid) || $rel['code'] == 200){
				foreach($parameter_id as $pid){
					$rel = model('ErpGoodsClasstempParameter') -> addData($classtemp_id, $pid);//插入新的关联规格id
					if($rel['code'] < 0){
						$this->error($rel['message']);
					}
				}
				$this->success('设置成功', null, '_parent_reload');
			}
			$this->error($rel['message']);
		}
		
		$parameter_id = model('ErpGoodsClasstempParameter') -> where('classtemp_id', $classtemp_id) -> column('parameter_id');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('参数设置')
			->addCheckbox('parameter_id', '选择参数', '选择参数不能超过20项', model('ErpParameter', 'model') -> column('id,title'), $parameter_id, 'multiple')
            ->setTrigger('auto_create', '1', 'child_node', false)
            ->fetch();
    }
	
}

